package com.threadpool.mythread.case01;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author 李李李
 * @2020/4/25 23:18
 *
 * 读写锁
 *
 * 独占锁 就是写锁
 * 共享锁 就是读锁
 *
 * 读 - 读 可以共存
 * 读 - 写 不可以共存
 * 写 - 写 不可以共存
 */
public class Case08 {
    public static void main(String[] args){
        MyCatch myCatch = new MyCatch();
        //写入
        for (int i = 0; i < 5; i++){
            final int temp = i;
            new Thread(()->{
                myCatch.put(temp+"", UUID.randomUUID().toString());
            },String.valueOf(i)).start();
        }

        //读取
        for (int i = 0; i < 5; i++){
            final int temp = i;
            new Thread(()->{
                myCatch.get(temp+"");
            },String.valueOf(i)).start();
        }
    }
}

class MyCatch{

    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    private volatile Map<String,String> myCatch = new HashMap(16);

    //写入
    public void put(String key,String value){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"开始写入数据");
            myCatch.put(key,value);
            System.out.println(Thread.currentThread().getName()+"写入成功");
        }finally {
            readWriteLock.writeLock().unlock();
        }
    }

    //读取
    public void get(String key){
        readWriteLock.readLock().lock();
        try {
            myCatch.get(key);
            System.out.println(Thread.currentThread().getName()+"读取数据成功");
        }finally {
            readWriteLock.readLock().unlock();
        }
    }
}
